{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at\n",
    "https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "\n",
    "FLAGS = None\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义各种激活函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [],
   "source": [
    "def swish(x):\n",
    "    return x*tf.nn.sigmoid(x)\n",
    "\n",
    "def selu(x):\n",
    "    with tf.name_scope(\"elu\") as scope:\n",
    "        alpha = 1.6732632423543772848170429916717 \n",
    "        scale = 1.0507009873554804934193349852946 \n",
    "        return scale*tf.where(x>=0.0, x, alpha*tf.nn.elu(x))\n",
    "\n",
    "def relu(x):\n",
    "    return tf.nn.relu(x) \n",
    "\n",
    "def sigmoid(x):\n",
    "    return tf.nn.sigmoid(x)\n",
    "\n",
    "def initialize(shape,stddev=0.1):\n",
    "    return tf.truncated_normal(shape,stddev=stddev)  #截断的高斯分布\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "准备数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-3-4b84739ca7dd>:3: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From c:\\python36\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please write your own downloading logic.\n",
      "WARNING:tensorflow:From c:\\python36\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting ./input_data/train-images-idx3-ubyte.gz\n",
      "WARNING:tensorflow:From c:\\python36\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting ./input_data/train-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From c:\\python36\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.one_hot on tensors.\n",
      "Extracting ./input_data/t10k-images-idx3-ubyte.gz\n",
      "Extracting ./input_data/t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From c:\\python36\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "data_dir = './input_data/'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "单隐层模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create the model\n",
    "def single(units_count,learning_rate,activat_func):   #参数分别为神经元数量，学习率，激活函数\n",
    "    init_learning_rate=tf.placeholder(tf.float32,[None,1])\n",
    "    L1_units_count=units_count   #神经元数量\n",
    "    x = tf.placeholder(tf.float32, [None, 784])\n",
    "    # tf.shape(x)[100,784]\n",
    "\n",
    "    epoch_steps=tf.to_int64(tf.div(60000,tf.shape(x)[0]))\n",
    "    global_step=tf.train.get_or_create_global_step()\n",
    "    current_epoch=global_step//epoch_steps  #epoch数量\n",
    "    decay_times=current_epoch\n",
    "    current_learning_rate=tf.multiply(init_learning_rate,tf.pow(learning_rate,tf.to_float(decay_times))) #学习率\n",
    "    W_1=tf.Variable(initialize([784,L1_units_count],stddev=np.sqrt(2/784)))  #使用的he初始化\n",
    "    b_1=tf.Variable(tf.constant(0.001,shape=[L1_units_count]))\n",
    "    logits_1=tf.add(tf.matmul(x,W_1),b_1)\n",
    "    output_1=activat_func(logits_1)\n",
    "\n",
    "    L2_units_count=10\n",
    "    W_2=tf.Variable(initialize([L1_units_count,L2_units_count],stddev=np.sqrt(2/units_count)))  #使用的he初始化,前一层共100个神经元\n",
    "    b_2=tf.Variable(tf.constant(0.001,shape=[L2_units_count]))\n",
    "    logits_2=tf.add(tf.matmul(output_1,W_2),b_2)\n",
    "    y=logits_2\n",
    "    \n",
    "    \n",
    "    y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "\n",
    "\n",
    "    cross_entropy = tf.reduce_mean(\n",
    "        tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n",
    "    train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n",
    "    sess = tf.Session()\n",
    "    init_op = tf.global_variables_initializer()\n",
    "    sess.run(init_op)\n",
    "    for _ in range(3000):\n",
    "      batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "      sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n",
    "    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "    print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                          y_: mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9744\n"
     ]
    }
   ],
   "source": [
    "single(100,0.575,swish)    #神经元100个，初始学习率位动态方差0.575的he初始化，激活函数是swish"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9648\n"
     ]
    }
   ],
   "source": [
    "single(28,0.575,swish)    #神经元28个，初始学习率位动态方差0.575的he初始化，激活函数是swish"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9775\n"
     ]
    }
   ],
   "source": [
    "single(200,0.575,swish)    #神经元200个，初始学习率位动态方差0.575的he初始化，激活函数是swish"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "神经元数量大一点，准确率更高，但考虑效率，不宜太大。暂设为200"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9753\n"
     ]
    }
   ],
   "source": [
    "single(200,0.45,swish)   #初始学习率位动态方差0.45的he初始化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9751\n"
     ]
    }
   ],
   "source": [
    "single(200,0.65,swish)   #初始学习率位动态方差0.65的he初始化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9763\n"
     ]
    }
   ],
   "source": [
    "single(200,0.6,swish)   #初始学习率位动态方差0.6的he初始化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9764\n"
     ]
    }
   ],
   "source": [
    "single(200,0.55,swish)   #初始学习率位动态方差0.6的he初始化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "初步来看，初始学习率位动态方差0.575的he初始化比较合适，正确率较高。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9787\n"
     ]
    }
   ],
   "source": [
    "single(200,0.575,relu)    #激活函数是relu"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9695\n"
     ]
    }
   ],
   "source": [
    "single(200,0.575,selu)    #激活函数是selu"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9558\n"
     ]
    }
   ],
   "source": [
    "single(200,0.575,sigmoid)    #激活函数是sigmoid"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "总体来看，激活函数用relu正确率最高，达到0.9787"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "结论：单隐层，初始学习率位动态方差0.575的he初始化比，激活函数用relu。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "双隐层"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {},
   "outputs": [],
   "source": [
    "def double(units_count_1,units_count_2,learning_rate,activat_func):   #参数分别为L1层神经元数量，L2层神经元数量，学习率，激活函数\n",
    "    init_learning_rate=tf.placeholder(tf.float32,[None,1])\n",
    "    L1_units_count=units_count_1   #神经元数量\n",
    "    x = tf.placeholder(tf.float32, [None, 784])\n",
    "    # tf.shape(x)[100,784]\n",
    "\n",
    "    epoch_steps=tf.to_int64(tf.div(60000,tf.shape(x)[0]))\n",
    "    global_step=tf.train.get_or_create_global_step()\n",
    "    current_epoch=global_step//epoch_steps  #epoch数量\n",
    "    decay_times=current_epoch\n",
    "    current_learning_rate=tf.multiply(init_learning_rate,tf.pow(learning_rate,tf.to_float(decay_times))) #学习率\n",
    "    W_1=tf.Variable(initialize([784,L1_units_count],stddev=np.sqrt(2/784)))  #使用的he初始化\n",
    "    b_1=tf.Variable(tf.constant(0.001,shape=[L1_units_count]))\n",
    "    logits_1=tf.add(tf.matmul(x,W_1),b_1)\n",
    "    output_1=activat_func(logits_1)\n",
    "\n",
    "    L2_units_count=units_count_2\n",
    "    W_2=tf.Variable(initialize([L1_units_count,L2_units_count],stddev=np.sqrt(2/units_count_1)))  #使用的he初始化,前一层共100个神经元\n",
    "    b_2=tf.Variable(tf.constant(0.001,shape=[L2_units_count]))\n",
    "    logits_2=tf.add(tf.matmul(output_1,W_2),b_2)\n",
    "    output_2=activat_func(logits_2)\n",
    "    \n",
    "    L3_units_count=10\n",
    "    W_3=tf.Variable(initialize([L2_units_count,L3_units_count],stddev=np.sqrt(2/units_count_2)))  #使用的he初始化,前一层共28个神经元\n",
    "    b_3=tf.Variable(tf.constant(0.001,shape=[L3_units_count]))\n",
    "    logits_3=tf.add(tf.matmul(output_2,W_3),b_3)\n",
    "    y=logits_3\n",
    "    \n",
    "    \n",
    "    y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "\n",
    "\n",
    "    cross_entropy = tf.reduce_mean(\n",
    "        tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n",
    "    train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n",
    "    sess = tf.Session()\n",
    "    init_op = tf.global_variables_initializer()\n",
    "    sess.run(init_op)\n",
    "    for _ in range(3000):\n",
    "      batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "      sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n",
    "    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "    print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                          y_: mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.979\n"
     ]
    }
   ],
   "source": [
    "double(200,100,0.575,relu)   #第一层200个神经元，第二层100个神经元"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9809\n"
     ]
    }
   ],
   "source": [
    "double(190,100,0.575,relu)   #第一层200个神经元，第二层100个神经元"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9768\n"
     ]
    }
   ],
   "source": [
    "double(210,100,0.575,relu)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "第一层190，第二层100时，正确率达到98%以上"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9796\n"
     ]
    }
   ],
   "source": [
    "double(185,100,0.575,relu)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9755\n"
     ]
    }
   ],
   "source": [
    "double(195,100,0.575,relu)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "经过初调，第一层选190个神经元。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9787\n"
     ]
    }
   ],
   "source": [
    "double(190,95,0.575,relu)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.976\n"
     ]
    }
   ],
   "source": [
    "double(190,105,0.575,relu)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "结论：双隐藏模型，第一层190个神经元，第二层100个神经元，初始学习率位动态方差0.575的he初始化比，激活函数用relu时，正确率可以达到98%以上"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
